package com.beidouapp.common.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * @author fujian 系统参数配置
 */
@SuppressWarnings ("unchecked")
public class SystemConfig
{
    static Logger log = LoggerFactory.getLogger (SystemConfig.class);
    private static Map <String, String> configs = new HashMap <String, String> ();
    static
    {
        Resource resource = new ClassPathResource ("/META-INF/service/properties/config.properties");
        // 获取根下面的 config,xml文件 进行加载读取
        try
        {
        	Properties prop = new Properties();
        	prop.load(resource.getInputStream());
        	for(Map.Entry entry: prop.entrySet()){
        		configs.put((String)entry.getKey(), (String)entry.getValue());
        	}
        }
        catch (Exception ex)
        {
            log.error (ex.getMessage ());
            ex.printStackTrace ();
        }
    }

    public static String getConfig (String key)
    {
    	String pvalue = configs.get (key);
    	if(pvalue==null) return null;
    	Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}");
    	Matcher matcher = pattern.matcher(pvalue);
    	List<String> keyList = new ArrayList<String>();
    	while (matcher.find()) {
    		String vkey = matcher.group(1);
    		keyList.add(vkey);
        }
    	for(String keytemp : keyList){
    		String value = configs.get(keytemp);
    		pvalue = pvalue.replace("${"+keytemp+"}", value);
    	}
    	return pvalue;
    }


    public static String getAppDownLoadPage ()
    {
        return getConfig ("APP_DOWNLOAD_URL");
    }

}
